/*
 * Record.cpp
 *
 *  Created on: 16/04/2011
 *      Author: maruuchis
 */

#include "Record.h"


Record::Record(int length, char* dataRecord ) {
   this->buildRecord(dataRecord);
}
Record::Record(string key, int offset) {
  this->key = key;
  this->data = new vector<int>;
  this->data->push_back(offset);
}

vector<int> *Record::getData() const
{
    return data;
}

string Record::getKey() const
{
    return key;
}

void Record::setData(vector<int> *data)
{
    this->data = data;
}

void Record::setKey(string key)
{
    this->key = key;
}

int Record::getBytes(){
	//longitud de los offset, longitud de la clave, metada offset y clave
	return (this->data->size()*sizeof(int)) + this->getKey().size() + (sizeof(int)*2);

}

void Record::buildRecord(char *dataRecord){
//   Longitud de la clave
	int* pkeyLength = (int*)(dataRecord);
	int keyLength = *pkeyLength;
//  Tomo la clave que es una cadena de chars
//  char *key = new char[keyLength]; //nuevo
    char *pKey = (char*)(dataRecord + sizeof(int)); //el del archivo
	for (int i = 0; i < keyLength; i++) {
		this->key+= pKey[i] ;
	}
//longitud del vector de enteros
    int* dataLength = (int*)(dataRecord + sizeof(int) + keyLength);
    int length = *dataLength;
//  leo entero por entero y cargo el vector
    char* offsetStart = dataRecord + keyLength + (sizeof(int)*2);
    this->data = new vector<int>;
    for(int i = 0; i < length;i++){
    	int offset = *(int*)(offsetStart+(i*sizeof(int)));
    	this->data->push_back(offset);
    }
}

char* Record::BuildRecordStream() {
//  creo el buffer donde voy a guardar todo
	char* buffer = new char[this->getBytes()];
	int bufferPosition = 0;
// guardo la longitud de la clave
	*(int*)(buffer + bufferPosition) = this->getKey().size();
	bufferPosition += sizeof(int);
//guardo la clave caracter por caracter
	int cant = this->getKey().size();
	for (int i = 0; i < cant; i++) {
		*(buffer + bufferPosition) = this->key.at(i);
		bufferPosition += sizeof(char) ;
	}
//guardo el tamanio del vector
	*(int*)(buffer + bufferPosition) = this->getData()->size();
	bufferPosition += sizeof(int);
//guardo elemento por elemento del vector
	int cant2 = this->getData()->size();
	for (int i = 0; i < cant2; i++) {
		*(int*)(buffer + bufferPosition + (i*sizeof(int))) = this->getData()->at(i);
	}
	bufferPosition += (this->getData()->size())*sizeof(int);

	return buffer;
}
int Record::searchOffset(int offset){
	for (unsigned int i = 0; i<this->getData()->size();i++){
		if (this->getData()->at(i)== offset){
			return i;
		}
	}
    return -1;
}

/* Adds a new offset value to the collection.
 * Checks if the offset was added before, and if it wasn't, it adds it.
 */
void Record::insertOffset(int offset){

	if (this->searchOffset(offset) == -1)
		this->data->push_back(offset);
}
Record::~Record() {
	delete this->data;
}

int Record::getOffsetsNumber(int length, int *keyLength){
    return (length - sizeof (int) - *keyLength) / sizeof (int);
}
